package org.lex.swing.graph;

import java.awt.BorderLayout;
import java.awt.Window;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

import org.lex.swing.graph.ProgressModel.Range;
import org.lex.swing.widgets.EnhancedDialog;


public class DebugGraphDialog extends EnhancedDialog implements ProgressListener {
	private final JLabel label = new JLabel();
	private JTable table = null;
	private final GraphTableModel tableModel;

	public DebugGraphDialog(Window owner, final ProgressModel model) {
		super(owner);
		this.setTitle("Debug");
		model.addGraphListener(this);
		tableModel = new GraphTableModel(model);
		JPanel pane = new JPanel(new BorderLayout());
		pane.add(label, BorderLayout.NORTH);
		pane.add(new JScrollPane(this.getTable()), BorderLayout.CENTER);
		this.setContentPane(pane);
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				model.removeGraphListener(DebugGraphDialog.this);
			}
		});
	}

	private JTable getTable() {
		if (null == table) {
			table = new JTable(tableModel);
		}
		return table;
	}

	@Override
	public void boundsChanged(ProgressEvent e) {
		this.updateGraphModel(e.getModel());
	}

	@Override
	public void rangesAdded(ProgressEvent e) {
		this.updateGraphModel(e.getModel());
	}

	@Override
	public void rangesRemoved(ProgressEvent e) {
		this.updateGraphModel(e.getModel());
	}

	private void updateGraphModel(ProgressModel model) {
		StringBuilder buf = new StringBuilder();
		buf.append("Max=").append(model.getMaximum());
		buf.append(", count=").append(model.getRangeCount());
		label.setText(buf.toString());
		if (null != tableModel)
			tableModel.fireTableDataChanged();
	}

	private static class GraphTableModel extends AbstractTableModel {
		private static final String[] COLUMN_NAMES = { "#", "start", "end" };
		private final ProgressModel graph;

		public GraphTableModel(ProgressModel graph) {
			this.graph = graph;
		}

		@Override
		public Class<?> getColumnClass(int column) {
			if (0 == column)
				return Integer.class;
			else
				return Long.class;
		}

		@Override
		public String getColumnName(int column) {
			return COLUMN_NAMES[column];
		}

		@Override
		public int getColumnCount() {
			return COLUMN_NAMES.length;
		}

		@Override
		public int getRowCount() {
			return graph.getRangeCount();
		}

		@Override
		public Object getValueAt(int row, int column) {
			if (0 == column)
				return row;
			Range r = graph.getRange(row);
			if (1 == column)
				return r.start;
			else
				return r.end;
		}
	}
}
